package com.smartthinking.dive;


import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;

import com.google.android.gms.internal.bu;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class Registro extends Activity {
	private Spinner spinner;
	private Button btnciudad, btregistro;
	private int edo_cve=0;
	private String[] datos;
	public ListView listView1;
	private EditText et_nombre, et_paterno, et_materno, et_mail, et_telefono;
	String	html, estado;
	

	public void BotonCiudad(View view) {
		//		anun=3;
		new AsyncBusquedaAnunciantes().execute();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_registro);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		btnciudad = (Button) findViewById(R.id.spinner);
		btregistro = (Button) findViewById(R.id.bt_registro);
		et_nombre = (EditText) findViewById(R.id.et_nombre);
		et_paterno = (EditText) findViewById(R.id.et_paterno);
		et_materno = (EditText) findViewById(R.id.et_materno);
		et_mail = (EditText) findViewById(R.id.et_mail);
		et_telefono = (EditText) findViewById(R.id.et_telefono);

		btregistro.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String datos = isDataComplete();
				if(datos.equals("")){
//					Toast.makeText(getApplicationContext(), "envio", Toast.LENGTH_LONG).show();
					new AsyncRegister().execute();
				}else{
					AlertDialog.Builder builder = new AlertDialog.Builder(Registro.this);
					builder.setTitle("Aviso");
					builder.setMessage(""+datos);
					builder.setNeutralButton("Aceptar", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					AlertDialog dialog = builder.create();
					dialog.show();
				}
			}
		});



	}


	protected String isDataComplete() {
		if(et_nombre.getText().toString().equals(""))
			return "Escriba el nombre";
		if(et_paterno.getText().toString().equals(""))
			return "Escriba el apellido paterno";
		if(et_materno.getText().toString().equals(""))
			return "Escriba el apellido materno";
		if(et_mail.getText().toString().equals(""))
			return "Escriba el correo electrónico";
//		if(et_telefono.getText().toString().equals(""))
//			return "Escriba el tel�fono";
		if(edo_cve == 0){
			return "Seleccione un estado";
		}
		return "";

	}


	public class AsyncBusquedaAnunciantes extends AsyncTask<Void, Integer, Void>{

		ArrayList<Dictionary<String, String> > listaCategoria = null;
		ArrayList<Dictionary<String, String> > listaSubcategoria = null;
		ArrayList<Dictionary<String, String> > listaCiudad = null;
		int flig=0;
		ProgressBar bar;

		protected void onPreExecute() {
			super.onPreExecute();
			bar = (ProgressBar) findViewById(R.id.progressBar1);
			bar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			if(Utilities.isNetwork()){
				String url1="select * from estado order by edo_des";
				listaCiudad = Utilities.qry(getApplicationContext(),url1.replace(" ", "%20"));
//				edo_cve = Integer.parseInt(listaCiudad.get(0).get("edo_cve"));
				flig=2;
				
			}else{
//				String url1="select * from estado order by edo_des";
//				listaCiudad = Utilities.qry2(getApplicationContext(),url1);
//				edo_cve = Integer.parseInt(listaCiudad.get(0).get("edo_cve"));
				flig=3;
			}
			
			
			return null;
		}

		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			bar.setVisibility(View.INVISIBLE);
			if(flig == 3){
				AlertDialog.Builder builder = new AlertDialog.Builder(Registro.this);
				builder.setTitle("Aviso");
				builder.setMessage(R.string.st_se_perdi_la_conexi_n_a_internet);
				builder.setNeutralButton("Aceptar", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog dialog = builder.create();
				dialog.show();
			}else{
				datos = new String[listaCiudad.size()];
				for(int i=0; i<listaCiudad.size(); i++){
					datos[i] = listaCiudad.get(i).get("edo_des");
				}

				final Dialog dialog = new Dialog(Registro.this);
				dialog.setContentView(R.layout.lista_empresa);
				dialog.setTitle("Selecciona una ciudad:");

				ArrayAdapter<String> adaptador = new ArrayAdapter<String>(Registro.this,
						android.R.layout.simple_list_item_1, datos);

				listView1 = (ListView)dialog.findViewById(R.id.listViewempresa);
				listView1.setAdapter(adaptador);
				listView1.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> a, View v, int position,
							long id) {
						edo_cve = Integer.parseInt(listaCiudad.get(position).get("edo_cve"));
						estado = listaCiudad.get(position).get("edo_des");
						
						
						Log.i("edo_cve", ""+edo_cve);
						btnciudad.setText(datos[position]+ "");
						dialog.dismiss();
					}
				});
				dialog.show();
			}
			

		}
	}
	
	
	public class AsyncRegister extends AsyncTask<Void, Void, Void>{
		ArrayList<Dictionary<String, String>> insertData;
		ProgressBar bar;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			bar = (ProgressBar) findViewById(R.id.progressBar1);
			bar.setVisibility(View.VISIBLE);
			
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			if(Utilities.isNetwork()){
				/***INSERT A LA BASE DE DATOS***/
				
				
				String cadena = "INSERT INTO clientes(cli_idr, cli_nombre, cli_paterno, cli_materno, cli_mail, " +
						"cli_telefono,edo_cve, usu_udid)select (select coalesce((max(cli_idr)%2B1),1)from clientes), " +
						"'"+et_nombre.getText().toString()+"','"+et_paterno.getText().toString()+"'," +
								"'"+et_materno.getText().toString()+"','"+et_mail.getText().toString()+"'," +
										" '"+et_telefono.getText().toString()+"', "+edo_cve+", " +
												"'"+Utilities.getUDID(getApplicationContext())+"'";
				insertData = Utilities.qry3(getApplicationContext(), ""+cadena.replace(" ", "%20"));
				if(insertData.size() > 0){
					if(insertData.get(0).get("RETURN").equals("1")){
						Log.i("insert correcto", "insert correcto");
						SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
						SharedPreferences.Editor editor = preferences.edit();
						editor.putString("isregistered", "si").commit();
						finish();
						startActivity(new Intent(getApplicationContext(), Principal.class));

						
					}else{
						Log.i("fallo al insert", "fallo al insert");
					}
				}else{
					Log.i("size", ""+insertData.size());
				}
				
				
				/***ENV�O CORREO***/

//				if(listaAsistencia.size() > 0){

				String telefono;
				if(et_telefono.getText().toString().equals("")){
					telefono = "sin número";
				}else{
					telefono = ""+et_telefono.getText().toString();
				}
				
				html="Nombre: "+et_nombre.getText().toString()+"<br>"+
									 "Apellido paterno: "+et_paterno.getText().toString()+"<br>"+
									 "Apellido materno: "+et_materno.getText().toString()+"<br>"+
									 "Teléfono: "+telefono+"<br>"+
									 "Estado: "+estado+"<br>"+
									 "E-mail: "+et_mail.getText().toString()+"<br>";
//				}else{
//					flag=1;
//				}

				String querymail="EnviaMail=1&Email=dive@squenda.com.mx&Asunto=Registro&Texto="+html;
//				String querymail="EnviaMail=1&Email=joseluis-cadena@hotmail.com&Asunto=Registro&Texto="+html;


					ArrayList<Dictionary<String, String>> listaAsistencia1 = Utilities.qry4(Registro.this, querymail.replace(" ", "%20"));
					if(listaAsistencia1.size()>0){
						if(listaAsistencia1.get(0).get("respuesta").equals("1")){
							Log.i("Correo enviado", "Correo enviado");
						}else{
							Log.i("error al enviar", "error al enviar");

						}
					}
					else{
						Log.i("error de consulta", "error de consulta");

					}
				
				
			}else{
				
				
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Log.i("onpost", "onpost");
			bar.setVisibility(View.INVISIBLE);


			
		}
		
	}
	
	
	
}
